﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using XDCCManager.Network.IRC;

namespace XDCCManager.Windows
{
	/// <summary>
	/// Interaction logic for StartupWindow.xaml
	/// </summary>
	public partial class StartupWindow : Window
	{
		public StartupWindow()
		{
			InitializeComponent();
		}

		private void ServerList_Close(object sender, EventArgs e)
		{
			Close();
		}

		private void ServerList_Connect(object sender, EventHandlers.ServerEventArgs e)
		{
			ShowProgress();
			ServerConnection.Instance.Server = e.Server;
			ServerConnection.Instance.Connect();
		}

		private void progress_CancelRequested(object sender, EventArgs e)
		{
			ServerConnection.Instance.CancelConnect();
		}

		void Server_ConnectionReady(object sender, EventArgs e)
		{
			Application.Current.Dispatcher.BeginInvoke(new Action(() =>
			{
				HideProgress();
				XDCCManager.Model.ServerContext serverContext = FindResource("ServerContextDataSource") as XDCCManager.Model.ServerContext;
				serverContext.CurrentServer = ServerConnection.Instance.Server;
				App.Current.MainWindow = new MainWindow();
				App.Current.MainWindow.Show();
				Close();
			}));
		}

		void Server_ConnectionFailure(object sender, XDCCManager.Network.ConnectionErrorEventArgs e)
		{
			Application.Current.Dispatcher.BeginInvoke(new Action(() =>
			{
				MessageBox.Show(e.Message, "Error");
				HideProgress();
			}));
		}

		void Server_ConnectionStateUpdate(object sender, XDCCManager.Network.ConnectionStateEventArgs e)
		{
			Application.Current.Dispatcher.BeginInvoke(new Action(() =>
			{
				progress.Message = e.Message;
			}));
		}

		private void ShowProgress()
		{
			progress.ResetState();
			progress.Visibility = System.Windows.Visibility.Visible;
			progress.Begin();
		}

		private void HideProgress()
		{
			progress.End();
			progress.Visibility = System.Windows.Visibility.Collapsed;
		}

		private void window_Loaded(object sender, RoutedEventArgs e)
		{
			ServerConnection.Instance.ConnectionStateUpdate += Server_ConnectionStateUpdate;
			ServerConnection.Instance.ConnectionFailure += Server_ConnectionFailure;
			ServerConnection.Instance.ConnectionReady += Server_ConnectionReady;
		}

		private void window_Closed(object sender, EventArgs e)
		{
			ServerConnection.Instance.ConnectionStateUpdate -= Server_ConnectionStateUpdate;
			ServerConnection.Instance.ConnectionFailure -= Server_ConnectionFailure;
			ServerConnection.Instance.ConnectionReady -= Server_ConnectionReady;
		}
	}
}
